/**
 * The parser for xml. This is incredibly slow. Kind of just threw it together.
 * @author cathbar
 */
package com.dylankenny.flikrreader.model.parse;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.dylankenny.flikrreader.model.data.Feed;
import com.dylankenny.flikrreader.model.data.FeedItem;
import com.dylankenny.flikrreader.model.data.Media;

/**
 * @author cathbar
 */
public class XMLReader {

	/**
	 * Obviously, parse an xml string, and return a Feed.
	 * 
	 * @author cathbar
	 * @param xml
	 * @return
	 */
	public static Feed parseXML(String xml) {
		Feed feed = null;
		try {

			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			Document doc = dBuilder.parse(new ByteArrayInputStream(xml.getBytes()));

			doc.getDocumentElement().normalize();

			NodeList nList = doc.getElementsByTagName("entry");

			feed = new Feed();
			ArrayList<FeedItem> items = new ArrayList<FeedItem>();
			for (int temp = 0; temp < nList.getLength(); temp++) {

				Node nNode = nList.item(temp);

				if (nNode.getNodeType() == Node.ELEMENT_NODE) {
					FeedItem feedItem = new FeedItem();

					Element eElement = (Element) nNode;

					final String title = eElement.getAttribute("title");

					final String link = eElement.getElementsByTagName("link").item(1).getAttributes().getNamedItem("href").getTextContent();

					final String published = eElement.getElementsByTagName("published").item(0).getTextContent();

					final String dateTaken = eElement.getElementsByTagName("flickr:date_taken").item(0).getTextContent();

					feedItem.setDate_taken(dateTaken);
					feedItem.setLink(link);

					Media media = new Media();
					media.setM(link);
					feedItem.setMedia(media);

					feedItem.setPublished(published);
					feedItem.setTitle(title);

					items.add(feedItem);
				}
			}
			FeedItem[] itemsArray = new FeedItem[items.size()];
			itemsArray = (items.toArray(itemsArray));
			feed.setItems(itemsArray);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return feed;
	}

}
